// pages/movie/more-movie/more-movie.js
var app = getApp();
var util = require("../../../util/util.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    movies: [],
    categoryTitle:""
  },

  /**
   * 生命周期函数--监听页面加载
   * 
   */
  onLoad: function(options) {
    var categoryTitle = options.category;
    this.data.categoryTitle = categoryTitle;
    
    var dataUrl = "";
    switch (categoryTitle) {
      case "正在热映":
        dataUrl = app.globalData.doubanBase + "/v2/movie/in_theaters";
        break;
      case "即将上映":
        dataUrl = app.globalData.doubanBase + "/v2/movie/coming_soon";
        break;
      case "豆瓣Top250":
        dataUrl = app.globalData.doubanBase + "/v2/movie/top250";
        break;

      default:
        break;
    }
    this.data.refreshUrl = dataUrl;
    util.http(dataUrl, this.processDouban);
    
  },

  processDouban: function(movieDouban) {
    var movies = [];
    for (var index in movieDouban.subjects) {
      var subject = movieDouban.subjects[index];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + "...";
      }
      var temp = {
        stars: util.convertToStartsArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp)
      //隐藏loading状态
      
    }

    var totalMovies = []
    totalMovies = this.data.movies.concat(movies);
    this.setData({
      movies: totalMovies
    })
    wx.stopPullDownRefresh();
    wx.hideNavigationBarLoading();
  },
 
  //点击电影进入详情页面
  onMovieTap: function (event) {
    var movieId = event.currentTarget.dataset.movieId;
    wx.navigateTo({
      url: '../movie-detail/movie-detail?id=' + movieId
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // 动态设置导航栏标题
    wx.setNavigationBarTitle({
      title: this.data.categoryTitle,
    })
    //显示loading状态
    wx.showNavigationBarLoading();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   * 下来刷新
   */
  onPullDownRefresh: function() {
    var refreshUrl = this.data.refreshUrl + "?start=0&count=20";
    this.data.movies = [];
    util.http(refreshUrl, this.processDouban);
    //显示loading状态
    // wx.showNavigationBarLoading();
  },

  /**
   * 页面上拉触底事件的处理函数
   * 上拉加载
   */
  onReachBottom: function() {
    var totalCount = this.data.movies.length;
    var nextUrl = this.data.refreshUrl + "?start=" + totalCount + "&count=20";
    util.http(nextUrl, this.processDouban);
    //显示loading状态
    wx.showNavigationBarLoading();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})